from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *

iap_coupon_project_api = Blueprint('iap_coupon_project_api', __name__)
iap_coupon_project_down_api = Blueprint('iap_coupon_project_down_api', __name__)

@iap_coupon_project_api.route('/iap_coupon_project', methods=['POST'])
def iap_coupon_project():
    params = json.loads(request.data)
    action = params['action']
    project = params['project']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}

    if action == 'basic':
        query = IapCouponProject.query.filter_by(project=project).first()
        iap_list = getIapList(1)

        iap_list.append({
            'value': 36000,
            'label': '$199.99-36000'
        })
        # iap_list.append({
        #     'value': 90000,
        #     'label': '$499.99-90000'
        # })

        chest = json.loads(query.chest)
        total_group = 0
        task_tabs = []
        tabIndex = 0
        for i in range(len(chest)):
            tmp = {
                'title': f'礼包{i+1}', 'name': str(i+1)
            }
            task_tabs.append(tmp)
            total_group += 1
            tabIndex = max(tabIndex, i)

        troop_control = loadDynamicSubGame()['open_control']['troop_control']
        ages = []
        age_list = []
        troop_control_default = troop_control['default']
        troop_control_special = troop_control['special']
        for node in troop_control_default:
            if node not in ages:
                ages.append(node)
        for node in troop_control_special:
            for open_node in node['open']:
                if open_node not in ages:
                    ages.append(open_node)
        ages.sort()
        for age in ages:
            age_list.append({
                'label': f'时代{age+1}',
                'value': age
                })

        evips = loadSubGame()['sub_game_evip_v2']['lv_conf']
        evip_lv_list = []
        for i in range(len(evips)):
            evip_lv_list.append({
                'label': f'等级{i+1}',
                'value': i+1
                })

        doc_id_list = GetDocByFilenameNew('stockpile_pack_event')
        pay_level_type_list = read_s3_file('pay_level_type_list')
        pay_level_type_list.append({"name": "全部用户可见", "value": -1, "pay_level_id": []})
        basic_data = json.loads(query.basic)
        if 'event_ui' not in basic_data:
            basic_data['event_ui'] = 1
        tmp = {
            'project': int(query.project),
            'basic': basic_data,
            'chest': chest,
            'iap_list': iap_list,
            'total_group': total_group,
            'task_tabs': task_tabs,
            'tabIndex': tabIndex,
            'age_list': age_list,
            'evip_lv_list': evip_lv_list,
            'doc_id_list': doc_id_list,
            'pay_level_type_list': pay_level_type_list
        }
        result_data['data']['item'] = tmp

    elif action == 'update_basic':
        basic = params['basic_data']
        chest = params['chest']
        IapCouponProject.query.filter_by(project=project).update({
            'basic': json.dumps(basic), 'chest': json.dumps(chest)
        })
        db.session.commit()
        result_data['data']['msg'] = "更新成功"

    return jsonify(result_data)

@iap_coupon_project_down_api.route("/iap_coupon_project_down/<int:is_push>", methods=['POST', 'GET'])
def DownAction(is_push):
    result = {}
    query = IapCouponProject.query.order_by('project').all()
    gem_map_price = getIapList(2)

    gem_map_price[36000] = 200
    # gem_map_price[90000] = 500

    pay_level_type_list = read_s3_file('pay_level_type_list')
    pay_level_type_list.append({"name": "全部用户可见", "value": -1, "pay_level_id": []})
    visible_crowd_list = {}
    for node in pay_level_type_list:
        visible_crowd_list[str(node['value'])] = node['pay_level_id']
    # print(visible_crowd_list, flush=True)
    for que in query:
        project = str(que.project)
        basic = json.loads(que.basic)
        chest = json.loads(que.chest)
        remark = que.remark

        doc_id = basic['doc_id']
        event_ui = basic['event_ui'] if 'event_ui' in basic else 1
        project_list = []

        chest_id = 0
        for node in chest:
            chest_id += 1
            node['reward']['0'] = RewardToTMysqlNew(node['reward']['0'])
            node['reward']['1'] = RewardToTMysqlNew(node['reward']['1'])
            node['reward']['2'] = RewardToTMysqlNew(node['reward']['2'])
            node['reward']['free_bonus'] = RewardToTMysqlNew(node['reward']['free_bonus'])
            # print(project, node['basic'], node['basic']['visible_crowd'], flush=True)
            proj_tmp = {
                'project_id': chest_id,
                'gems': node['basic']['gems'],
                'iap': gem_map_price[node['basic']['gems']],
                'ui': node['basic']['ui'],
                'castle_lv': [
                    node['basic']['castle_lv_left'],
                    node['basic']['castle_lv_right']],
                'sid': [
                    node['basic']['sid_left'],
                    node['basic']['sid_right']],
                'epoch_id': [
                    node['basic']['epoch_id_left'],
                    node['basic']['epoch_id_right']],
                'evip_lv': [
                    node['basic']['evip_lv_left'],
                    node['basic']['evip_lv_right']],
                'visible_crowd': visible_crowd_list[str(node['basic']['visible_crowd'])],
                'bonus': node['reward']['free_bonus'],
                'extra_bonus': {
                    '0': node['reward']['0'],
                    '1': node['reward']['1'],
                    '2': node['reward']['2']
                }
            }
            project_list.append(proj_tmp)

        tmp = {
            'remark': remark,
            'localization_doc': {
                'title': doc_id,
                'info': doc_id
            },
            'project_list': project_list,
            'event_ui': event_ui
        }
        result[project] = tmp

    response = DownLoad('iap_coupon_project', result, is_push)

    return response
